package com.ljd.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ljd.server.pojo.MailConstants;
import com.ljd.server.pojo.MailLog;
import com.ljd.server.service.IMailLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 邮件发送定时任务
 *
 * @author ljd on 2022/2/6
 * @PACKAGE_NAME: com.ljd.server.task
 * @PROJECT_NAME: yeb
 */
@Component
public class MailTask {


    @Autowired
    private IMailLogService mailLogService;


    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask() {
        List<MailLog> list = mailLogService.list(
                new QueryWrapper<MailLog>()
                        .eq("status", 0)
                        .lt("tryTime", LocalDateTime.now()));
        list.forEach(mailLog -> {
            // 如果重试次数大于3,说明投递失败,将状态改为失败,不再重试
            if (3 <= mailLog.getCount()) {
                mailLogService.update(
                        new UpdateWrapper<MailLog>()
                                .set("status", 2)
                                .eq("msgId", mailLog.getMsgId()));
            }
            mailLogService.update(
                    new UpdateWrapper<MailLog>()
                            .set("count", mailLog.getCount() + 1)
                            .set("updateTime", LocalDateTime.now())
                            .set("tryTime",LocalDateTime.now().plusHours(MailConstants.MSG_TIMEOUT)));

        });


    }
}
